package com.zfzs.post.service.impl;

import com.zfzs.post.enums.DayType;
import com.zfzs.post.exception.BadRequestException;
import com.zfzs.post.model.dto.MerchantReportDTO;
import com.zfzs.post.model.dto.MineMerchantDTO;
import com.zfzs.post.model.dto.QueryMerchantPageDTO;
import com.zfzs.post.model.dto.QueryMerchantPageListDTO;
import com.zfzs.post.model.vo.QueryAddMerchantListVO;
import com.zfzs.post.modules.agent.service.dto.AgentDTO;
import com.zfzs.post.modules.banner.domain.BannerInfo;
import com.zfzs.post.modules.banner.service.BannerInfoService;
import com.zfzs.post.modules.merchant.domain.Merchant;
import com.zfzs.post.modules.merchant.service.MerchantService;
import com.zfzs.post.modules.merchant.service.mybatis.IMerchantervice;
import com.zfzs.post.modules.post.domain.TerminalInfo;
import com.zfzs.post.modules.post.service.PostTerminalDistribuService;
import com.zfzs.post.modules.post.service.TerminalInfoService;
import com.zfzs.post.modules.post.service.TerminalTypeService;
import com.zfzs.post.modules.transaction.service.TransactionInfoService;
import com.zfzs.post.page.JpaPageHelper;
import com.zfzs.post.service.JwtUserDetailsService;
import com.zfzs.post.service.MerchantApiService;
import com.zfzs.post.service.TerminalService;
import com.zfzs.post.utils.BigDecimalUtil;
import com.zfzs.post.utils.DateStrUtils;
import com.zfzs.post.model.vo.QueryTranTopTenVO;
import com.zfzs.post.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wq
 * @date 2019/9/26 11:08
 * @description
 */
@Service
public class MerchantApiServiceImpl implements MerchantApiService {

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private IMerchantervice iMerchantervice;

    @Autowired
    private TransactionInfoService transactionInfoService;

    @Autowired
    private BannerInfoService bannerInfoService;

    @Autowired
    private TerminalInfoService terminalService;

    @Autowired
    private TerminalTypeService terminalTypeService;

    @Autowired
    private PostTerminalDistribuService terminalDistribuService;


    @Override
    public void reportMerchant(MerchantReportDTO dto) {
        AgentDTO info = jwtUserDetailsService.getAgentInfo();
        //验证sn
        String sn = dto.getSn();
        Merchant m = merchantService.findBySn(sn);
        TerminalInfo terminalInfo = terminalService.findBySN(sn);
        if (terminalInfo == null) {
            throw new BadRequestException("没有查询到机具数据");
        }
        Long channelId = terminalInfo.getChannelId();
        if (!channelId.equals(info.getChannelId())) {
            throw new BadRequestException("此机器不属于您的渠道");
        }
        //校验机器是否属于自己
        Long agentId = terminalDistribuService.findOwnerBySn(sn);
        if (info.getId().intValue() != agentId.intValue()) {
            throw new BadRequestException("此机器不属于您的名下");
        }
        Merchant merchant = new Merchant();
        merchant.setAgentId(info.getId());
        merchant.setCreateTime(new Timestamp(System.currentTimeMillis()));
        merchant.setMerchantName(dto.getMerchantName());
        merchant.setPhone(dto.getPhone());
        //设置sn
        merchant.setSn(dto.getSn());
        merchant.setTerminalTypeId(terminalInfo.getTerminalTypeId());
        merchant.setStatus(0L);
        merchant.setRegStatus(1L);
        merchant.setChannelId(channelId);
        if (m == null) {
            merchantService.create(merchant);
        } else {
            //修改
            if (m.getStatus() == 0) {
                throw new BadRequestException("此机具已经完成报备");
            }
            merchant.setId(m.getId());
            merchantService.create(merchant);
        }
        terminalInfo.setIsReport(1L);
        terminalService.update(terminalInfo);
    }

    @Override
    public Map<String, Object> mineMerchant(MineMerchantDTO dto) {
        Map<String, Object> map = new HashMap<>();
        String tranType = dto.getTranType();
        String startDate = dto.getStartDate();
        String endDate = dto.getEndDate();
        AgentDTO info = jwtUserDetailsService.getAgentInfo();
        Long id = info.getId();
        //商户总数
        int totalCount = merchantService.countMerchant(id);
        map.put("totalCount", totalCount);
        if (StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
            //默认本月时间
            Map<String, String> day = DateStrUtils.getStartAndEndDate(DayType.TO_MONTH);
            if (day == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDate = day.get("startDate");
            endDate = day.get("endDate");
        }
        //总交易额
        BigDecimal totalSum = transactionInfoService.queryTransactionSumByDate(id, startDate, endDate);
        if ("total".equals(tranType)) {
            map.put("totalSum", totalSum);
        } else if ("average".equals(tranType)) {
            int count = transactionInfoService.queryTransactionCountByDate(id, startDate, endDate);
            Double TerminalAll = new Double(totalSum.doubleValue());
            Double TerminalCount = new Double(count);
            System.out.println("=======" + TerminalAll);
            System.out.println("=======" + TerminalCount);
            BigDecimal averageSum = BigDecimalUtil.div(TerminalAll, TerminalCount);
            //台均额
            map.put("totalSum", averageSum);
        } else {
            throw new BadRequestException("参数tranType错误");
        }
        //沉默商户
        int silenceCount = merchantService.silenceMerchant(id);
        map.put("silenceCount", silenceCount);
        //优质商户
        int highCount = merchantService.highMerchant(id);
        map.put("highCount", highCount);
        //banner图
        BannerInfo b = new BannerInfo();
        b.setTypes("merchant");
        b.setStatus(true);
        List<BannerInfo> bannerInfoList = bannerInfoService.queryBannerList(b);
        map.put("bannerImgUrl", bannerInfoList.get(0).getImgUrl());
        //TOP10商户列表
        List<QueryTranTopTenVO> list = merchantService.queryTranTopTenList(id,startDate,endDate);
        map.put("list", list);
        return map;
    }

    @Override
    public Map<String, Object> queryMerchantPageList(QueryMerchantPageListDTO dto) {
        Map<String, Object> resMap = new HashMap<>();
        AgentDTO agent = jwtUserDetailsService.getAgentInfo();
        dto.setAgentId(agent.getId());
        dto.setChannelId(agent.getChannelId());
        //维度查询 YESTER_DAY:昨日 今日：TO_DAY 当月：TO_MONTH 本季：TO_SEASON 全年:TO_YEAR
        String weiDuType = dto.getWeiDuType();
        String startDay = "";
        String endDay = "";
        String tranStartDay = "";
        String tranEndDay = "";
        if (StringUtils.isNotEmpty(weiDuType)) {
            Map<String, String> map = DateStrUtils.getStartAndEndDate(weiDuType);
            if (map == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDay = map.get("startDate");
            endDay = map.get("endDate");
        } else {
            //默认本月时间
            Map<String, String> map = DateStrUtils.getStartAndEndDate(DayType.TO_MONTH);
            if (map == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            startDay = map.get("startDate");
            endDay = map.get("endDate");
        }
        String transactionType = dto.getTransactionType();
        if (StringUtils.isNotEmpty(transactionType)) {
            Map<String, String> map = DateStrUtils.getStartAndEndDate(transactionType);
            if (map == null) {
                throw new BadRequestException("交易类型参数错误");
            }
            tranStartDay = map.get("startDate");
            tranEndDay = map.get("endDate");
        } else {
            //默认本月时间
            Map<String, String> map = DateStrUtils.getStartAndEndDate(DayType.TO_MONTH);
            if (map == null) {
                throw new BadRequestException("维度类型参数错误");
            }
            tranStartDay = map.get("startDate");
            tranEndDay = map.get("endDate");
        }
        dto.setTranEndDay(tranEndDay);
        dto.setTranStartDay(tranStartDay);
        dto.setStartDay(startDay);
        dto.setEndDay(endDay);
        String yearDayTotalSum = iMerchantervice.queryMerchantPageSum(dto);
        JpaPageHelper page = iMerchantervice.findAgentPageList(dto);
        resMap.put("list", page.getResult());
        resMap.put("totalCount", page.getTotalCount());
        resMap.put("yearDayTotalSum", yearDayTotalSum);
        return resMap;
    }

}
